use sqlx::Row;
use std::path::Path;

#[derive(Debug)]
pub struct BinaryFile {
    pub id: u64,
    pub file_name: String,
    pub file_type: String,
    pub file_data: Vec<u8>,
    pub created_at: chrono::DateTime<chrono::Utc>,
}
// 存储文件到数据库
pub async fn store_binary(file_name: &str, file_data: Vec<u8>) -> anyhow::Result<u64> {
    // 获取文件名
    // let idx = file_name
    //     .chars()
    //     .position(|c| c == '.')
    //     .ok_or_else(|| anyhow::anyhow!("文件名中没有扩展名"))?;
    // let file_type = &file_name[idx..];

    let path = Path::new(file_name);
    let file_type = path.extension()
        .and_then(|ext| ext.to_str());

    // 插入数据库
    let result = sqlx::query(
        r#"
        INSERT INTO sys_binary_files (file_name, file_type, file_data)
        VALUES (?, ?, ?)
        "#,
    )
    .bind(file_name)
    .bind(file_type)
    .bind(&file_data as &[u8])
    .execute(get_my_pool())
    .await?;
    // 返回插入的ID
    Ok(result.last_insert_id())
}
use crate::prelude::get_my_pool;
// 从数据库读取文件并保存到本地
pub async fn retrieve_binary_file(file_id: u64) -> anyhow::Result<BinaryFile> {
    // 查询文件
    let row= sqlx::query(
        r#"
        SELECT id, file_name, file_type, file_data, created_at
        FROM sys_binary_files
        WHERE id = ?
        "#,
    )
    .bind(file_id)
    .fetch_one(get_my_pool())
    .await?;
    let file_name: String = row.try_get("file_name")?;
    let file_type: String = row.try_get("file_type")?;
    let file_data: Vec<u8> = row.try_get("file_data")?;
    let created_at: chrono::DateTime<chrono::Utc> = row.try_get("created_at")?;
    Ok(BinaryFile {
        id: file_id,
        file_name,
        file_type,
        file_data,
        created_at,
    })
}
